//
//  RTJTenderDetailsController.m
//  RuiTaiJinProject
//
//  Created by jayson on 2018/12/3.
//  Copyright © 2018年 leewei. All rights reserved.
//

#import "RTJTenderDetailsController.h"
#import "MXSegmentedPager.h"
#import "MXParallaxHeader.h"
#import "MXScrollViewController.h"
#import "RTJProductController.h"
#import "RTJContractController.h"
#import "RTJLendRecordController.h"
#import "RTJImmediatelyLendController.h"


#define  BAR_HEIGHT 54

@interface RTJTenderDetailsController ()<MXSegmentedPagerDelegate,MXSegmentedPagerDataSource,UINavigationBarDelegate,UIScrollViewDelegate>


@property (weak, nonatomic) IBOutlet UIView  *headView;//头部视图
@property (nonatomic,weak) IBOutlet MXSegmentedPager *segmentedPager;
@property (weak, nonatomic) IBOutlet UIView *bg_view;
@property (weak, nonatomic) IBOutlet UIView *bg_view1;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftCenter;

@property (nonatomic,strong) RTJProductController *suggestCoursesVC;
@property (nonatomic,strong) RTJContractController *simmarSchoolsVC;
@property (nonatomic,strong) RTJLendRecordController *videosVC;
@property (weak, nonatomic) IBOutlet UILabel *subname;
@property (weak, nonatomic) IBOutlet UILabel *rebateLab;
@property (weak, nonatomic) IBOutlet UILabel *time_type;

@property (weak, nonatomic) IBOutlet UILabel *rateLab;
@property (weak, nonatomic) IBOutlet UIImageView *tipsImg;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tipWidth;
@property (weak, nonatomic) IBOutlet UILabel *numLab;

@property (weak, nonatomic) IBOutlet UILabel *timeLab;
@property (weak, nonatomic) IBOutlet UILabel *remainLab;

@property (weak, nonatomic) IBOutlet UILabel *shouyiLab;

@property (weak, nonatomic) IBOutlet UIImageView *img1;
@property (weak, nonatomic) IBOutlet UIImageView *img2;
@property (weak, nonatomic) IBOutlet UIImageView *img3;
@property (weak, nonatomic) IBOutlet UIImageView *img4;
@property (weak, nonatomic) IBOutlet UIImageView *img5;

@property (weak, nonatomic) IBOutlet UILabel *lab1;
@property (weak, nonatomic) IBOutlet UILabel *lab2;
@property (weak, nonatomic) IBOutlet UILabel *lab3;
@property (weak, nonatomic) IBOutlet UILabel *lab4;
@property (weak, nonatomic) IBOutlet UILabel *lab5;

@property (weak, nonatomic) IBOutlet UILabel *lendMoney;
@property (weak, nonatomic) IBOutlet UILabel *remainTime;

@property (nonatomic, strong) NSDictionary *dataSource;

@property (weak, nonatomic) IBOutlet UIButton *lendBtn;
@property (weak, nonatomic) IBOutlet UILabel *qitouzijin;

@property (weak, nonatomic) IBOutlet UIView *navigationBarView;
@property (weak, nonatomic) IBOutlet UILabel *nav_title;
@property (strong, nonatomic) IBOutlet UIButton *backButtonItem;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nav_height;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nav_top;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *center;
@property (nonatomic,strong ) NSString *timeType;

@end

@implementation RTJTenderDetailsController

-(void)reloadPagers {
    
    if (_suggestCoursesVC) {
        [_suggestCoursesVC removeFromParentViewController];
        _suggestCoursesVC = nil;
    }
    
    if (_simmarSchoolsVC) {
        [_simmarSchoolsVC removeFromParentViewController];
        _simmarSchoolsVC = nil;
    }
    
    if (_videosVC) {
        [_videosVC removeFromParentViewController];
        _videosVC = nil;
    }
    
    [self.segmentedPager reloadData];
}


-(RTJProductController *)suggestCoursesVC {
    if ( ! _suggestCoursesVC) {
        if ( ! self.dataSource) {
            return nil;
        }
        _suggestCoursesVC = [[RTJProductController alloc] init];
        _suggestCoursesVC.data = self.dataSource;
        [self addChildViewController:_suggestCoursesVC];
        [_suggestCoursesVC didMoveToParentViewController:self];
    }
    
    return _suggestCoursesVC;
}

-(RTJContractController *)simmarSchoolsVC {
    if ( ! _simmarSchoolsVC) {
        if ( ! self.dataSource) {
            return nil;
        }
        
        _simmarSchoolsVC = [[RTJContractController alloc] init];
        _simmarSchoolsVC.content = self.dataSource[@"deal_info"][@"risk_security"];
        [self addChildViewController:_simmarSchoolsVC];
        [_simmarSchoolsVC didMoveToParentViewController:self];
    }
    
    return _simmarSchoolsVC;
}

-(RTJLendRecordController *)videosVC {
    if ( ! _videosVC) {
        if ( ! self.dataSource) {
            return nil;
        }
    
        _videosVC = [[RTJLendRecordController alloc] init];
        _videosVC.data = self.dataSource;
        [self addChildViewController:_videosVC];
        [_videosVC didMoveToParentViewController:self];
    }
    
    return _videosVC;
}

-(void)viewWillAppear:(BOOL)animated{

    self.navigationController.navigationBarHidden = YES;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;

    [self backview:_bg_view viewOfcornerRadius:5];
    [self backview:_bg_view1 viewOfcornerRadius:5];
    self.nav_height.constant = screenH == 812 ? 88 : 64;
    self.nav_top.constant = screenH == 812 ? 52 : 28;

    self.segmentedPager.delegate = self;
    self.segmentedPager.dataSource = self;
    self.segmentedPager.bounces = NO;
    self.segmentedPager.backgroundColor = [UIColor whiteColor];
    
    // header view
    self.segmentedPager.parallaxHeader.view = self.headView;
    self.segmentedPager.parallaxHeader.height = 691;
    self.segmentedPager.parallaxHeader.mode = MXParallaxHeaderModeBottom; // 平行底部填充模式
    self.segmentedPager.parallaxHeader.minimumHeight = screenH == 812 ? 98 : 74; // 头部最小高度
    
    // 选择栏控制器属性
    self.segmentedPager.segmentedControl.borderWidth = 1.0; // 边框宽度
    self.segmentedPager.segmentedControl.borderColor = [UIColor redColor]; // 边框颜色
    self.segmentedPager.segmentedControl.frame = CGRectMake(0, 0, screenW, 44); // frame
    self.segmentedPager.segmentedControl.segmentEdgeInset = UIEdgeInsetsMake(-10, 0, 0, 0);// 间距
    self.segmentedPager.segmentedControl.selectionIndicatorHeight =3;// 横条指示器高度
    // 底部指示器的宽度等于内容宽度
    self.segmentedPager.segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
    self.segmentedPager.segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
    self.segmentedPager.segmentedControl.verticalDividerEnabled = NO;// 不可以垂直滚动
    self.segmentedPager.segmentedControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleFixed;
    self.segmentedPager.segmentedControl.selectionIndicatorColor = [UIColor colorForHex:@"#FD3734"];
    // 默认状态的字体
    self.segmentedPager.segmentedControl.titleTextAttributes =
    @{NSForegroundColorAttributeName : [UIColor colorForHex:@"#999999"],
      NSFontAttributeName : [UIFont systemFontOfSize:16]};
    // 选择状态下的字体
    self.segmentedPager.segmentedControl.selectedTitleTextAttributes =
    @{NSForegroundColorAttributeName : [UIColor colorForHex:@"#333333"],
      NSFontAttributeName : [UIFont systemFontOfSize:16]};
  
    self.segmentedPager.segmentedControlEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    

    [self loadData];
    

}

-(void)backview:(UIView *)backview viewOfcornerRadius:(NSInteger)cornerRadius{
    
    backview.layer.cornerRadius = cornerRadius;
    backview.layer.shadowColor = [UIColor colorForHex:@"#dbc9cc"].CGColor;
    backview.layer.shadowOffset = CGSizeMake(-1, 1);
    backview.layer.shadowOpacity = 0.5;
    backview.layer.shadowRadius = 5;
    
}


// 滚动整体的时候调用
- (void)segmentedPager:(MXSegmentedPager *)segmentedPager didScrollWithParallaxHeader:(MXParallaxHeader *)parallaxHeader
{
    
    CGFloat alpha = [self calcNavigationBarBlendAlpha]<(screenH ==812 ? 0.192:0.25) ? 0 :[self calcNavigationBarBlendAlpha];
    
    [self setNavigationBarBlendAlpha:alpha animation:YES];
    
    
}

-(CGFloat)calcNavigationBarBlendAlpha {
    UIScrollView *scrollView = (UIScrollView *)self.segmentedPager.subviews[0];
    CGFloat offsetY = scrollView.contentOffset.y;
    
    // 上滑一定距离，导航显示
    return ((screenH ==812 ? -132 : -108)/offsetY);
}

-(void)setNavigationBarBlendAlpha:(CGFloat)alpha animation:(BOOL)animation {
    
    
    if (animation) {
        [UIView animateWithDuration:UINavigationControllerHideShowBarDuration delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
            
            self.navigationBarView.alpha = alpha;
            self.backButtonItem.alpha = alpha;
            self.nav_title.alpha = alpha;
            
        } completion:nil];
    }
    
}

#pragma -mark <MXSegmentedPagerDelegate>

- (CGFloat)heightForSegmentedControlInSegmentedPager:(MXSegmentedPager *)segmentedPager
{
    // 指示栏的高度
    return 44.0f;
}

#pragma -mark <MXSegmentedPagerDataSource>

- (NSInteger)numberOfPagesInSegmentedPager:(MXSegmentedPager *)segmentedPager
{
    return 3;
}

- (NSString *)segmentedPager:(MXSegmentedPager *)segmentedPager titleForSectionAtIndex:(NSInteger)index
{
    // 指示栏的文字数组
    return [@[@"标的信息", @"安全保障", @"出借记录"] objectAtIndex:index];
}

- (UIView *)segmentedPager:(MXSegmentedPager *)segmentedPager viewForPageAtIndex:(NSInteger)index
{
    UIViewController *vc;
    
    switch (index) {
        case 0:
            vc = self.suggestCoursesVC;
            break;
            
        case 1:
            vc = self.simmarSchoolsVC;
            break;
            
        case 2:
            vc = self.videosVC;
            break;
    }
    
    if ( ! vc) {
        return nil;
    }
    return vc.view;
}

- (void)segmentedPager:(MXSegmentedPager *)segmentedPager didSelectViewWithIndex:(NSInteger)index
{
    UIScrollView *scrollView = (UIScrollView *)segmentedPager.subviews[0];
    NSLog(@"%lf",scrollView.contentOffset.x);
    
    if (index==0) {
        
    }else if (index==1) {
   
    }
    else if (index==2) {
        
    }
    
}

- (IBAction)lend:(id)sender {

    if ([RTJUserTool isLogin]) {
        
        NSInteger rebate = [self.dataSource[@"deal_info"][@"user_bid_rebate"] integerValue];

        
        RTJImmediatelyLendController *lend = [[RTJImmediatelyLendController alloc]init];
        lend.titleStr = _subname.text;
        lend.timeStr = [NSString stringWithFormat:@"%@",self.dataSource[@"deal_info"][@"repay_time"]];
        
        NSString *string =[NSString stringWithFormat:@"%@",_dataSource[@"deal_info"][@"rate"]];
        NSArray *arr = [string componentsSeparatedByString:@"."]; //字符串分隔成数组
        NSString *str = [NSString stringWithFormat:@"%@",arr[0]];
        lend.rateStr = str;
        lend.time_typeStr = _timeType;
        lend.remainStr = [NSString stringWithFormat:@"%@",_dataSource[@"deal_info"][@"need_money_format"]];
        lend.rebateStr = rebate == 0 ? @"" : [NSString stringWithFormat:@"%@",self.dataSource[@"deal_info"][@"user_bid_rebate"]];
        lend.idStr = [NSString stringWithFormat:@"%@",_dataSource[@"deal_info"][@"id"]];
        lend.max_mon = [self.dataSource[@"deal_info"][@"max_loan_money"] integerValue];
        lend.min_mon = [self.dataSource[@"deal_info"][@"min_loan_money"] integerValue];
        
        [self.navigationController pushViewController:lend animated:YES];
        
    }else{
        
        RTJLoginOrRegisterController *vc = [[RTJLoginOrRegisterController alloc]init];
        LXNavigationViewController *nav=[[LXNavigationViewController alloc]initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:nil];
        
    }
    

}


- (IBAction)back:(id)sender {

    [self.navigationController popViewControllerAnimated:YES];

}

-(void)loadData{
    
    [SVProgressHUD  showWithStatus:nil];
    
    if (_dataSource == nil) {
        
        [self.view showEmptyViewWithStr:@"" image:nil callback:nil];
            
    }
    
    [RTJNetWork asyncRequestWithURL:@"deals/detail" params:@{@"id":_markId} method:GET zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        [SVProgressHUD dismiss];
        
        [self.view removeEmptyView];
        
        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {
                
                self.dataSource = data[@"data"];
                
                [self loadHeaderView:self.dataSource];
                
                [self reloadPagers];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",data[@"msg"]]];
                
                [self.view showEmptyViewWithStr:errorMsg image:[UIImage imageNamed:@"kbylogo"] callback:^{
                    
                    [self loadData];
                }];
                
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
            [self.view showEmptyViewWithStr:errorMsg image:[UIImage imageNamed:@"kbylogo"] callback:^{
                
                [self loadData];
            }];

        }        
        
    }];
    
    
}

-(void)loadHeaderView:(NSDictionary *)dic{
    
    
    NSString *string =[NSString stringWithFormat:@"%@",dic[@"deal_info"][@"rate"]];
    NSArray *arr = [string componentsSeparatedByString:@"."]; //字符串分隔成数组
    
    NSString *str = [NSString stringWithFormat:@"%@",arr[0]];
//    _rateLab.text = [NSString stringWithFormat:@"%@",arr[0]];
    
    NSInteger repay_time_type = [dic[@"deal_info"][@"repay_time_type"] integerValue];
    
    if (repay_time_type == 0) {
        _timeType = @"天";
    }else if (repay_time_type == 1){
        _timeType = @"个月";
    }else{
        _timeType = @"年";
    }
    
    _subname.text = [NSString stringWithFormat:@"%@",dic[@"deal_info"][@"name"]];
    _nav_title.text = [NSString stringWithFormat:@"%@",dic[@"deal_info"][@"name"]];
    _numLab.text = [NSString stringWithFormat:@"%@%@",dic[@"deal_info"][@"progress_point"],@"%"];
    
    NSString *str1 = [NSString stringWithFormat:@"%@",dic[@"deal_info"][@"progress_point"]];
    
    
    _tipWidth.constant = _tipsImg.width *[str1 floatValue]/100;
    
   
    
    NSString *time = [NSString stringWithFormat:@"%@%@",dic[@"deal_info"][@"repay_time"],_timeType];
    _timeLab.attributedText = [self getSubStrNumFromStr:time WithLocation:time.length-2 frontStr:18 behindStr:12 fontName:YES];

    NSString *qitou = [NSString stringWithFormat:@"%@元",dic[@"deal_info"][@"min_loan_money_format"]];
    _qitouzijin.attributedText = [self getSubStrNumFromStr:qitou WithLocation:qitou.length-1 frontStr:18 behindStr:12 fontName:YES];
    
    NSString *shengyu = [NSString stringWithFormat:@"%@元",dic[@"deal_info"][@"need_money_format"]];
    _remainLab.attributedText = [self getSubStrNumFromStr:shengyu WithLocation:shengyu.length-1 frontStr:18 behindStr:12 fontName:YES];
    
    if ([shengyu isEqualToString:@"0.00元"]) {
        
        _lendBtn.userInteractionEnabled = NO;
        [_lendBtn setTitle:@"已满标" forState:UIControlStateNormal];
        [_lendBtn setBackgroundImage:[UIImage imageNamed:@"btn_qrcjhui"] forState:UIControlStateNormal];
        
    }else{
        
        [_lendBtn setBackgroundImage:[UIImage imageNamed:@"btn_ljcj"] forState:UIControlStateNormal];
        [_lendBtn setTitle:@"立即出借" forState:UIControlStateNormal];
        _lendBtn.userInteractionEnabled = YES;
        
    }

    _lendMoney.text = [NSString stringWithFormat:@"¥ %@ 元",dic[@"deal_info"][@"borrow_amount_thousand_format"]];
    _remainTime.text = [NSString stringWithFormat:@"%@",dic[@"deal_info"][@"remain_time_format"]];
    
    NSInteger rebate = [dic[@"deal_info"][@"user_bid_rebate"] integerValue];

    
    if (rebate == 0) {
        
        if (str.length == 2) {
            
            str = [NSString stringWithFormat:@"%@%@",str,@"%"];
            _rateLab.attributedText = [self getSubStrNumFromStr:str WithLocation:2 frontStr:34 behindStr:20 fontName:NO];
            
        }else{
            
            str = [NSString stringWithFormat:@"%@%@",str,@"%"];
            _rateLab.attributedText = [self getSubStrNumFromStr:str WithLocation:1 frontStr:34 behindStr:20 fontName:NO];
            
        }
        
    }else{
        
        if (str.length == 2) {
            
            str = [NSString stringWithFormat:@"%@%@+%ld%@",str,@"%",rebate,@"%"];
            _rateLab.attributedText = [self getSubStrNumFromStr:str WithLocation:1 frontStr:34 behindStr:20 fontName:NO];
            
        }else{
            
            str = [NSString stringWithFormat:@"%@%@+%ld%@",str,@"%",rebate,@"%"];
            _rateLab.attributedText = [self getSubStrNumFromStr:str WithLocation:1 frontStr:34 behindStr:20 fontName:NO];
            
        }
    }
    
    CGFloat rebate1 = [dic[@"deal_info"][@"user_bid_rebate"] floatValue];//加息

    //收益 = 投标金额*（预期年化*/100/12）*投资期限
    
    CGFloat rete = [dic[@"deal_info"][@"rate"] floatValue];
    
    CGFloat repay_time = [dic[@"deal_info"][@"repay_time"] floatValue];
    
    CGFloat shouyi = 10000*((rete+rebate1)/100/12)*repay_time;
    
    _shouyiLab.text = [NSString stringWithFormat:@"%.2f",shouyi];
    
    
    _lab5.text = [dic[@"deal_info"][@"loantype"]integerValue] ==1 ?@"付息还本":@"到期还本";
    
    NSInteger deal_status = [dic[@"deal_info"][@"deal_status"] integerValue];//12等待满标 4 满标计息  5还清  3 流标
    
    if (deal_status == 1||deal_status == 2) {
        
        _lab1.textColor = [UIColor colorForHex:@"#FE623C"];
        _lab2.textColor = [UIColor colorForHex:@"#999999"];
        
        _lab3.textColor = [UIColor colorForHex:@"#FE623C"];
        _lab4.textColor = [UIColor colorForHex:@"#999999"];
        _lab5.textColor = [UIColor colorForHex:@"#999999"];
        
        _img1.image = [UIImage imageNamed:@"icon_cjlcxs1"];
        _img2.image = [UIImage imageNamed:@"icon_cjlcbxs2"];
        _img3.image = [UIImage imageNamed:@"icon_cjlcbxs3"];
        
        _img4.image = [UIImage imageNamed:@"icon_fzxhong"];
        _img5.image = [UIImage imageNamed:@"icon_fzxhui"];
        
        
    }else if (deal_status == 4){
        
        _lab1.textColor = [UIColor colorForHex:@"#FE623C"];
        _lab2.textColor = [UIColor colorForHex:@"#FE623C"];
        
        _lab3.textColor = [UIColor colorForHex:@"#FE623C"];
        _lab4.textColor = [UIColor colorForHex:@"#FE623C"];
        _lab5.textColor = [UIColor colorForHex:@"#999999"];
        
        _img1.image = [UIImage imageNamed:@"icon_cjlcxs1"];
        _img2.image = [UIImage imageNamed:@"icon_cjlcxs2"];
        _img3.image = [UIImage imageNamed:@"icon_cjlcbxs3"];
        
        _img4.image = [UIImage imageNamed:@"icon_fzxhong"];
        _img5.image = [UIImage imageNamed:@"icon_fzxhong"];
        
    }else{
        
        _lab1.textColor = [UIColor colorForHex:@"#FE623C"];
        _lab2.textColor = [UIColor colorForHex:@"#FE623C"];
        
        _lab3.textColor = [UIColor colorForHex:@"#FE623C"];
        _lab4.textColor = [UIColor colorForHex:@"#FE623C"];
        _lab5.textColor = [UIColor colorForHex:@"#FE623C"];
        
        _img1.image = [UIImage imageNamed:@"icon_cjlcxs1"];
        _img2.image = [UIImage imageNamed:@"icon_cjlcxs2"];
        _img3.image = [UIImage imageNamed:@"icon_cjlcxs3"];
        
        _img4.image = [UIImage imageNamed:@"icon_fzxhong"];
        _img5.image = [UIImage imageNamed:@"icon_fzxhong"];
    }
    
}

- (NSMutableAttributedString *)getSubStrNumFromStr:(NSString *)str WithLocation:(NSInteger) index frontStr:(CGFloat) font1 behindStr:(CGFloat)font2 fontName:(BOOL)fontName{
    
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:str];
    
    [AttributedStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"PingFang-SC-Medium" size:font1] range:NSMakeRange(0, index)];
    
    [AttributedStr addAttribute:NSFontAttributeName value:fontName? [UIFont fontWithName:@"PingFang-SC-Regular" size:font2]: [UIFont fontWithName:@"PingFang-SC-Medium" size:font2] range:NSMakeRange(index, str.length-index)];
    
    return AttributedStr;
    
}

@end
